/**
 * Copyright (2017, ) Institute of Software, Chinese Academy of Sciences
 */
package cn.abcsys.cloud.devops.runtime.incubates.models;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.abcsys.cloud.devops.runtime.incubates.utils.UrlUtils;

/**
 * @author wuheng(wuheng@otcaix.iscas.ac.cn)
 * @date   Jul 10, 2017
 *
 */
public class Url implements Cloneable {

	protected final static Logger m_logger= Logger.getLogger(Url.class);
	
	protected final String url;
	
	public Url(String url) {
		super();
		this.url = url;
	}

	// url:[{IP1, IP2, Ip3}]
	protected List<String> hosts = new ArrayList<String>();
	
	/***********************************************************
	 * 
	 *                     Core methods
	 * 
	 **********************************************************/
	
	/**
	 * 添加url与hostIP的关联关系
	 * 比如，负载均衡涉及192.168.1.1/home,192.168.1.2/home,192.168.1.3/home
	 * 则url表示/home, hostIP为192.168.1.1,192.168.1.2,192.168.1.3
	 * 
	 * 如果存在，则覆盖原有的
	 * 
	 * @param url
	 * @param hostIP
	 */
	public void addHost(String hostIP) {
		if(invalid(hostIP)) {
			m_logger.info("url or hostIp is invalid");
		} else {
			hosts.add(hostIP);
			m_logger.info("add  (" + url + "," + hostIP + ")");
		}
	}
	
	public boolean addHostsIfExistNew(List<String> allHosts) {
		boolean isNew = (hosts.containsAll(allHosts) 
				&& hosts.size() == allHosts.size()) ? false : true;
		if(isNew) {
			hosts.addAll(allHosts);
		}
		return isNew;
	}

	/**
	 * 返回指定url的所有host列表，如果url不存在，则返回null
	 * 
	 * @param url
	 * @return
	 */
	public List<String> getHosts() {
		return hosts;
	}
	
	public String getUrl() {
		return url;
	}

	/***********************************************************
	 * 
	 *                     Other methods
	 * 
	 **********************************************************/
	/**
	 * @param url
	 * @param hostIP
	 * @return
	 */
	private boolean invalid(String hostIP) {
		return  UrlUtils.validIP(hostIP) ? false : true;
	}

	@Override
	public String toString() {
		return "Url [url2Hosts=" + hosts + "]";
	}
	
	protected Object clone() throws CloneNotSupportedException {
		Url url = (Url) super.clone();
		return url;
	}
}
